import React, { useState, memo, useEffect, useRef } from 'react';
import { Row, Col, message, Switch } from 'tdesign-react';
import { getListApi } from 'api/useManage/accunt';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import SakuraModal from 'components/SakuraModal';
import { IModalRef } from 'components/SakuraModal/types';
import { handleUpdateStatus, PARRENT_TYPE_OPTIONS, type_MAP } from './consts';
import IppeakTable from 'components/IppeakTable';
import StatusSwitch from 'components/StatusSwitch';

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, setLoading } = useLoading(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const modalRef = useRef<IModalRef | any>(null);

  const initData = {
    status: 1,
    pack_type: '1',
    order_type: 9,
    email: '',
  };
  const fields: any[] = [
    { label: '邮箱', name: 'email', type: 'input', required: true },
    {
      label: '套餐类型',
      name: 'pack_type',
      type: 'select',
      options: [{ label: '流量', value: 1 }],
      required: true,
      disabled: true,
    },
    { label: '流量', name: 'flow', type: 'input', required: true, appendSuffix: 'G' },
    { label: '时效', name: 'day', type: 'input', required: true, appendSuffix: '天' },
    {
      label: '订单类型',
      name: 'order_type',
      type: 'select',
      options: [],
      disabled: true,
      help: '试用订单仅对没有GB套餐的用户生效；',
    },
    { label: '备注', name: 'remarks', type: 'textarea', props: { autosize: { minRows: 3, maxRows: 10 } } },
  ];
  const columns = createColumns([
    {
      label: '用户ID',
      key: 'user_id',
    },
    {
      label: '邮箱',
      key: 'email',
      width: '200',
    },
    {
      label: 'Username',
      key: 'suname',
      width: '150',
    },
    {
      label: '流量上限',
      key: 'traffic_top',
      width: '150',
    },
    {
      label: '添加时间',
      key: 'created',
      type:'date',
      width: '150',
    },
    {
      label: '用户备注',
      key:'remarks',
      width: '150',
    },
    {
      label: '状态',
      key: 'region',
      render: ({ row }: any) => (
        <StatusSwitch
          value={row.activate}
          loading={updatingRows.has(row.id)}
          onChange={(newValue) => handleUpdateStatus(newValue, row, setUpdatingRows, setTable)}
          row={row}
          activeText="启用"
          inactiveText="禁用"
        />
      ),
    },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const [updatingRows, setUpdatingRows] = useState<Set<string | number>>(new Set());
  const formFields: any[] = [
    {
      label:'用户ID',
      name:'uid',
      type:'input',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    {
      label: '邮箱',
      name: 'email',
      type: 'input',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
    },
    {
      label:'状态',
      name:'status',
      type:'select',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
      options: [{ label: '启用', value: 1 }, { label: '禁用', value: 2 }],
    },
  ];
  const { list, total, current, pageSize } = table;
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      const res: any = await getListApi({ ...params, ...query });
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results || [],
        total: res.total || 0,
        pageSize: res.page_size || 10,
        current: res.page || 1,
      }));
    } catch (err) {
      console.log(err, 'err');
    }
  };
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleAddClick = () => {
    setVisible(true);
  };
  const handleSubmitClick = async (type: string, values: any, cb: () => void) => {
    try {
      if (type == 'Add') {
      } else {
      }
    } catch (err: any) {
      if (err.response.data.code == 40050) {
        message.error('邮箱错误或不存在');
        modalRef.current.setFieldError('email', '邮箱错误');
      }
      return;
    }
    cb && cb();
    fetchUserList();
    setVisible(false);
  };
  
  // 统一的 useEffect：组件挂载时和 query 变化时都会调用
  useEffect(() => {
    fetchUserList();
  }, [query]);
  const handleSearch = (values: any) => {
    setQuery((pre) => ({
      ...pre,
      ...values,
      page: 1,
    }));
  };
  const handleReset = () => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
    }));
  };
      // 统一的字段清除处理函数
      const handleFieldClear = (fieldName: string) => {
        setQuery((prev: any) => {
          const { [fieldName]: removed, ...rest } = prev || {};
          return { ...rest, };
        });
      };

  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm
            fields={formFields}
            onAddClick={handleAddClick}
            onSearch={handleSearch}
            onFieldClear={handleFieldClear}
            onReset={handleReset}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        tableHeight={272}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          onCurrentChange(current: number, pageInfo: any) {
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
          },
          onPageSizeChange(size: number) {
            setQuery((pre) => ({
              ...pre,
              page_size: size,
            }));
          },
        }}
      />
      <SakuraModal
        ref={modalRef}
        visible={visible}
        title={'订单'}
        onClose={() => {
          setVisible(false);
        }}
        onSubmit={handleSubmitClick}
        type={opType}
        initialValues={opType == 'Edit' ? editingItem : initData}
        fields={fields}
      ></SakuraModal>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
